<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DormDB 管理员面板</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Vue.js -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    
    <!-- Axios for HTTP requests -->
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.0/dist/axios.min.js"></script>
    
    <!-- Chart.js for statistics -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        /* 自定义样式 */
        .glass-effect {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .floating-animation {
            animation: float 6s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-20px); }
        }
        
        .pulse-animation {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .slide-in {
            animation: slideIn 0.5s ease-out;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .fade-in {
            animation: fadeIn 0.3s ease-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .shake {
            animation: shake 0.5s ease-in-out;
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }
        
        .loading-spinner {
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 表格样式 */
        .table-hover tbody tr:hover {
            background-color: #f8fafc;
        }
        
        /* 状态徽章 */
        .status-badge {
            @apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
        }
        
        .status-success {
            @apply bg-green-100 text-green-800;
        }
        
        .status-error {
            @apply bg-red-100 text-red-800;
        }
        
        .status-warning {
            @apply bg-yellow-100 text-yellow-800;
        }
        
        .status-info {
            @apply bg-blue-100 text-blue-800;
        }
    </style>
</head>
<body class="min-h-screen gradient-bg">
    <div id="app">
        <!-- 浮动装饰元素 -->
        <div class="fixed inset-0 overflow-hidden pointer-events-none">
            <div class="absolute top-10 left-10 w-20 h-20 bg-white bg-opacity-10 rounded-full floating-animation"></div>
            <div class="absolute top-1/4 right-20 w-16 h-16 bg-white bg-opacity-5 rounded-full floating-animation" style="animation-delay: -2s;"></div>
            <div class="absolute bottom-1/4 left-1/4 w-12 h-12 bg-white bg-opacity-15 rounded-full floating-animation" style="animation-delay: -4s;"></div>
            <div class="absolute bottom-10 right-10 w-24 h-24 bg-white bg-opacity-5 rounded-full floating-animation" style="animation-delay: -1s;"></div>
        </div>

        <!-- Toast 通知容器 -->
        <div class="fixed top-4 right-4 z-50 space-y-2">
            <transition-group name="toast" tag="div">
                <div v-for="toast in toasts" :key="toast.id" 
                     :class="`p-4 rounded-lg shadow-lg max-w-sm ${getToastClass(toast.type)} fade-in`">
                    <div class="flex items-center">
                        <i :class="getToastIcon(toast.type)" class="mr-3 text-lg"></i>
                        <div class="flex-1">
                            <div class="font-semibold">{{ toast.title }}</div>
                            <div v-if="toast.message" class="text-sm opacity-90">{{ toast.message }}</div>
                        </div>
                        <button @click="removeToast(toast.id)" class="ml-2 text-lg opacity-70 hover:opacity-100">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            </transition-group>
        </div>

        <!-- 登录模态框 -->
        <div v-if="!isAuthenticated" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-40 backdrop-blur-sm">
            <div class="glass-effect rounded-2xl p-8 max-w-md w-full mx-4 slide-in">
                <div class="text-center mb-8">
                    <div class="text-6xl mb-4 pulse-animation">
                        <i class="fas fa-tools text-white"></i>
                    </div>
                    <h2 class="text-2xl font-bold text-white mb-2">管理员登录</h2>
                    <p class="text-white text-opacity-80">请输入管理员密码访问控制面板</p>
                </div>
                
                <form @submit.prevent="login" class="space-y-6">
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-lock text-white text-opacity-60"></i>
                        </div>
                        <input v-model="loginPassword" 
                               type="password" 
                               placeholder="管理员密码"
                               :class="`w-full pl-10 pr-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-lg text-white placeholder-white placeholder-opacity-60 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50 transition-all ${loginError ? 'shake border-red-400' : ''}`"
                               required>
                    </div>
                    
                    <div v-if="loginError" class="text-red-300 text-sm text-center shake">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        {{ loginError }}
                    </div>
                    
                    <button type="submit" 
                            :disabled="isLoggingIn"
                            class="w-full bg-white bg-opacity-20 hover:bg-opacity-30 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300 flex items-center justify-center space-x-2 disabled:opacity-50">
                        <i v-if="isLoggingIn" class="fas fa-spinner loading-spinner"></i>
                        <i v-else class="fas fa-sign-in-alt"></i>
                        <span>{{ isLoggingIn ? '登录中...' : '登录' }}</span>
                    </button>
                </form>
                
                <div class="text-center mt-6">
                    <a href="/" class="text-white text-opacity-80 hover:text-opacity-100 transition-colors">
                        <i class="fas fa-arrow-left mr-2"></i>
                        返回主页
                    </a>
                </div>
            </div>
        </div>

        <!-- 主要内容 -->
        <div v-if="isAuthenticated" class="min-h-screen p-4">
            <!-- 头部 -->
            <header class="glass-effect rounded-2xl p-6 mb-6 slide-in">
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                        <div class="text-4xl text-white">
                            <i class="fas fa-tools"></i>
                        </div>
                        <div>
                            <h1 class="text-2xl font-bold text-white">DormDB 管理员面板</h1>
                            <p class="text-white text-opacity-80">系统管理与监控中心</p>
                        </div>
                    </div>
                    <div class="flex items-center space-x-4">
                        <button @click="refreshData" 
                                :disabled="isRefreshing"
                                class="bg-white bg-opacity-20 hover:bg-opacity-30 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center space-x-2 disabled:opacity-50">
                            <i :class="`fas fa-sync-alt ${isRefreshing ? 'loading-spinner' : ''}`"></i>
                            <span>{{ isRefreshing ? '刷新中...' : '刷新数据' }}</span>
                        </button>
                        <button @click="logout" class="bg-red-500 bg-opacity-80 hover:bg-opacity-100 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center space-x-2">
                            <i class="fas fa-sign-out-alt"></i>
                            <span>退出登录</span>
                        </button>
                    </div>
                </div>
            </header>

            <!-- 统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                <div class="glass-effect rounded-xl p-6 slide-in">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-white text-opacity-80 text-sm">总申请数</p>
                            <p class="text-2xl font-bold text-white">{{ systemStatus.total_applications || 0 }}</p>
                        </div>
                        <div class="text-3xl text-white text-opacity-60">
                            <i class="fas fa-database"></i>
                        </div>
                    </div>
                </div>
                
                <div class="glass-effect rounded-xl p-6 slide-in" style="animation-delay: 0.1s;">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-white text-opacity-80 text-sm">今日申请</p>
                            <p class="text-2xl font-bold text-white">{{ systemStatus.today_applications || 0 }}</p>
                        </div>
                        <div class="text-3xl text-white text-opacity-60">
                            <i class="fas fa-calendar-day"></i>
                        </div>
                    </div>
                </div>
                
                <div class="glass-effect rounded-xl p-6 slide-in" style="animation-delay: 0.2s;">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-white text-opacity-80 text-sm">系统状态</p>
                            <p class="text-lg font-semibold text-white flex items-center">
                                <span :class="getStatusIndicator(systemStatus.database_status)" class="w-3 h-3 rounded-full mr-2"></span>
                                {{ systemStatus.database_status || '检查中' }}
                            </p>
                        </div>
                        <div class="text-3xl text-white text-opacity-60">
                            <i class="fas fa-server"></i>
                        </div>
                    </div>
                </div>
                
                <div class="glass-effect rounded-xl p-6 slide-in" style="animation-delay: 0.3s;">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-white text-opacity-80 text-sm">运行时间</p>
                            <p class="text-lg font-semibold text-white">{{ systemStatus.uptime || '计算中' }}</p>
                        </div>
                        <div class="text-3xl text-white text-opacity-60">
                            <i class="fas fa-clock"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 标签页导航 -->
            <div class="glass-effect rounded-t-xl p-1 mb-0">
                <nav class="flex space-x-1">
                    <button v-for="tab in tabs" :key="tab.id"
                            @click="activeTab = tab.id"
                            :class="`px-6 py-3 rounded-lg font-medium transition-all duration-300 flex items-center space-x-2 ${
                                activeTab === tab.id 
                                    ? 'bg-white bg-opacity-20 text-white' 
                                    : 'text-white text-opacity-70 hover:text-opacity-100 hover:bg-white hover:bg-opacity-10'
                            }`">
                        <i :class="tab.icon"></i>
                        <span>{{ tab.name }}</span>
                    </button>
                </nav>
            </div>

            <!-- 标签页内容 -->
            <div class="glass-effect rounded-b-xl rounded-tr-xl p-6">
                <!-- 最近申请记录 -->
                <div v-if="activeTab === 'applications'" class="fade-in">
                    <h3 class="text-xl font-bold text-white mb-6 flex items-center">
                        <i class="fas fa-list mr-3"></i>
                        最近申请记录
                    </h3>
                    
                    <div v-if="recentApplications.length === 0" class="text-center py-12">
                        <div class="text-6xl text-white text-opacity-30 mb-4">
                            <i class="fas fa-inbox"></i>
                        </div>
                        <p class="text-white text-opacity-70">暂无申请记录</p>
                    </div>
                    
                    <div v-else class="space-y-4">
                        <div v-for="app in recentApplications" :key="app.identity_key"
                             class="bg-white bg-opacity-10 rounded-lg p-4 hover:bg-opacity-20 transition-all duration-300">
                            <div class="flex items-center justify-between">
                                <div class="flex-1">
                                    <div class="flex items-center space-x-3">
                                        <div class="text-white font-semibold">{{ app.identity_key }}</div>
                                        <span class="status-badge status-success">
                                            <i class="fas fa-check mr-1"></i>
                                            已申请
                                        </span>
                                    </div>
                                    <div class="text-white text-opacity-70 text-sm mt-1">
                                        数据库: {{ app.db_name }} | 用户: {{ app.db_user }}
                                    </div>
                                </div>
                                <div class="text-white text-opacity-60 text-sm">
                                    {{ formatDateTime(app.created_at) }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 学号管理 -->
                <div v-if="activeTab === 'students'" class="fade-in">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-xl font-bold text-white flex items-center">
                            <i class="fas fa-graduation-cap mr-3"></i>
                            学号管理
                        </h3>
                        <div class="flex space-x-2">
                            <button @click="studentSubTab = 'list'" 
                                    :class="`px-4 py-2 rounded-lg transition-all duration-300 ${
                                        studentSubTab === 'list' 
                                            ? 'bg-white bg-opacity-20 text-white' 
                                            : 'text-white text-opacity-70 hover:text-opacity-100'
                                    }`">
                                <i class="fas fa-list mr-2"></i>
                                学号列表
                            </button>
                            <button @click="studentSubTab = 'add'" 
                                    :class="`px-4 py-2 rounded-lg transition-all duration-300 ${
                                        studentSubTab === 'add' 
                                            ? 'bg-white bg-opacity-20 text-white' 
                                            : 'text-white text-opacity-70 hover:text-opacity-100'
                                    }`">
                                <i class="fas fa-plus mr-2"></i>
                                添加学号
                            </button>
                            <button @click="studentSubTab = 'import'" 
                                    :class="`px-4 py-2 rounded-lg transition-all duration-300 ${
                                        studentSubTab === 'import' 
                                            ? 'bg-white bg-opacity-20 text-white' 
                                            : 'text-white text-opacity-70 hover:text-opacity-100'
                                    }`">
                                <i class="fas fa-upload mr-2"></i>
                                批量导入
                            </button>
                        </div>
                    </div>

                    <!-- 学号统计 -->
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                        <div class="bg-white bg-opacity-10 rounded-lg p-4">
                            <div class="text-center">
                                <div class="text-2xl font-bold text-white">{{ studentStats.total_count || 0 }}</div>
                                <div class="text-white text-opacity-70 text-sm">总学号数</div>
                            </div>
                        </div>
                        <div class="bg-white bg-opacity-10 rounded-lg p-4">
                            <div class="text-center">
                                <div class="text-2xl font-bold text-green-300">{{ studentStats.applied_count || 0 }}</div>
                                <div class="text-white text-opacity-70 text-sm">已申请</div>
                            </div>
                        </div>
                        <div class="bg-white bg-opacity-10 rounded-lg p-4">
                            <div class="text-center">
                                <div class="text-2xl font-bold text-yellow-300">{{ studentStats.not_applied_count || 0 }}</div>
                                <div class="text-white text-opacity-70 text-sm">未申请</div>
                            </div>
                        </div>
                    </div>

                    <!-- 学号列表 -->
                    <div v-if="studentSubTab === 'list'" class="fade-in">
                        <div class="bg-white bg-opacity-10 rounded-lg overflow-hidden">
                            <div class="overflow-x-auto">
                                <table class="w-full table-hover">
                                    <thead class="bg-white bg-opacity-10">
                                        <tr>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-white text-opacity-80 uppercase tracking-wider">学号</th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-white text-opacity-80 uppercase tracking-wider">姓名</th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-white text-opacity-80 uppercase tracking-wider">班级</th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-white text-opacity-80 uppercase tracking-wider">申请状态</th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-white text-opacity-80 uppercase tracking-wider">数据库名</th>
                                            <th class="px-6 py-3 text-left text-xs font-medium text-white text-opacity-80 uppercase tracking-wider">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-white divide-opacity-10">
                                        <tr v-if="studentList.length === 0">
                                            <td colspan="6" class="px-6 py-12 text-center text-white text-opacity-70">
                                                <div class="text-4xl mb-4">
                                                    <i class="fas fa-user-graduate"></i>
                                                </div>
                                                暂无学号记录
                                            </td>
                                        </tr>
                                        <tr v-for="student in studentList" :key="student.id" class="hover:bg-white hover:bg-opacity-5">
                                            <td class="px-6 py-4 whitespace-nowrap text-white font-medium">{{ student.student_id }}</td>
                                            <td class="px-6 py-4 whitespace-nowrap text-white text-opacity-80">{{ student.student_name || '-' }}</td>
                                            <td class="px-6 py-4 whitespace-nowrap text-white text-opacity-80">{{ student.class_info || '-' }}</td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <span :class="`status-badge ${student.has_applied ? 'status-success' : 'status-warning'}`">
                                                    <i :class="`fas ${student.has_applied ? 'fa-check' : 'fa-clock'} mr-1`"></i>
                                                    {{ student.has_applied ? '已申请' : '未申请' }}
                                                </span>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-white text-opacity-80">{{ student.applied_db_name || '-' }}</td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                                                <button @click="editStudent(student)" class="text-blue-300 hover:text-blue-200 transition-colors">
                                                    <i class="fas fa-edit mr-1"></i>
                                                    编辑
                                                </button>
                                                <button @click="deleteStudent(student.id)" class="text-red-300 hover:text-red-200 transition-colors">
                                                    <i class="fas fa-trash mr-1"></i>
                                                    删除
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- 添加学号 -->
                    <div v-if="studentSubTab === 'add'" class="fade-in">
                        <div class="max-w-md">
                            <form @submit.prevent="addStudent" class="space-y-6">
                                <div>
                                    <label class="block text-white text-opacity-80 text-sm font-medium mb-2">
                                        <i class="fas fa-id-card mr-2"></i>
                                        学号
                                    </label>
                                    <input v-model="newStudent.student_id" 
                                           type="text" 
                                           placeholder="输入10位学号"
                                           pattern="[0-9]{10}"
                                           class="w-full px-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-lg text-white placeholder-white placeholder-opacity-60 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50 transition-all"
                                           required>
                                </div>
                                
                                <div>
                                    <label class="block text-white text-opacity-80 text-sm font-medium mb-2">
                                        <i class="fas fa-user mr-2"></i>
                                        姓名 (可选)
                                    </label>
                                    <input v-model="newStudent.student_name" 
                                           type="text" 
                                           placeholder="输入学生姓名"
                                           class="w-full px-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-lg text-white placeholder-white placeholder-opacity-60 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50 transition-all">
                                </div>
                                
                                <div>
                                    <label class="block text-white text-opacity-80 text-sm font-medium mb-2">
                                        <i class="fas fa-users mr-2"></i>
                                        班级 (可选)
                                    </label>
                                    <input v-model="newStudent.class_info" 
                                           type="text" 
                                           placeholder="输入班级信息"
                                           class="w-full px-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-lg text-white placeholder-white placeholder-opacity-60 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50 transition-all">
                                </div>
                                
                                <button type="submit" 
                                        :disabled="isAddingStudent"
                                        class="w-full bg-green-500 bg-opacity-80 hover:bg-opacity-100 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300 flex items-center justify-center space-x-2 disabled:opacity-50">
                                    <i v-if="isAddingStudent" class="fas fa-spinner loading-spinner"></i>
                                    <i v-else class="fas fa-plus"></i>
                                    <span>{{ isAddingStudent ? '添加中...' : '添加学号' }}</span>
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- 批量导入 -->
                    <div v-if="studentSubTab === 'import'" class="fade-in">
                        <div class="max-w-2xl">
                            <div class="mb-6">
                                <h4 class="text-lg font-semibold text-white mb-2">
                                    <i class="fas fa-upload mr-2"></i>
                                    批量导入学号
                                </h4>
                                <p class="text-white text-opacity-70 text-sm">
                                    支持CSV格式，每行一个学号，格式：学号,姓名,班级（姓名和班级可选）
                                </p>
                            </div>
                            
                            <div class="space-y-6">
                                <div>
                                    <label class="block text-white text-opacity-80 text-sm font-medium mb-2">
                                        学号数据
                                    </label>
                                    <textarea v-model="importData" 
                                              rows="10" 
                                              placeholder="2203010301,张三,计算机2022-3班&#10;2203010302,李四,计算机2022-3班&#10;2203010303"
                                              class="w-full px-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-lg text-white placeholder-white placeholder-opacity-60 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50 transition-all font-mono text-sm"></textarea>
                                </div>
                                
                                <div class="flex items-center">
                                    <input v-model="overwriteExisting" 
                                           type="checkbox" 
                                           id="overwrite" 
                                           class="mr-3 w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500">
                                    <label for="overwrite" class="text-white text-opacity-80 text-sm">
                                        覆盖已存在的学号
                                    </label>
                                </div>
                                
                                <button @click="batchImportStudents" 
                                        :disabled="isImporting || !importData.trim()"
                                        class="bg-blue-500 bg-opacity-80 hover:bg-opacity-100 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300 flex items-center space-x-2 disabled:opacity-50">
                                    <i v-if="isImporting" class="fas fa-spinner loading-spinner"></i>
                                    <i v-else class="fas fa-upload"></i>
                                    <span>{{ isImporting ? '导入中...' : '批量导入' }}</span>
                                </button>
                                
                                <div v-if="importResult" 
                                     :class="`p-4 rounded-lg ${importResult.success ? 'bg-green-500 bg-opacity-20 border border-green-500 border-opacity-30' : 'bg-red-500 bg-opacity-20 border border-red-500 border-opacity-30'}`">
                                    <h5 class="font-semibold text-white mb-2">
                                        <i :class="`fas ${importResult.success ? 'fa-check-circle' : 'fa-exclamation-circle'} mr-2`"></i>
                                        {{ importResult.success ? '导入完成' : '导入失败' }}
                                    </h5>
                                    <div v-if="importResult.success" class="text-white text-opacity-90 text-sm space-y-1">
                                        <p>成功导入: {{ importResult.data.imported_count }} 条</p>
                                        <p>更新记录: {{ importResult.data.updated_count }} 条</p>
                                        <div v-if="importResult.data.errors.length > 0">
                                            <p class="font-medium mt-2">错误信息:</p>
                                            <ul class="list-disc list-inside space-y-1">
                                                <li v-for="error in importResult.data.errors" :key="error">{{ error }}</li>
                                            </ul>
                                        </div>
                                    </div>
                                    <div v-else class="text-white text-opacity-90 text-sm">
                                        {{ importResult.message }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 系统管理 -->
                <div v-if="activeTab === 'system'" class="fade-in">
                    <h3 class="text-xl font-bold text-white mb-6 flex items-center">
                        <i class="fas fa-cogs mr-3"></i>
                        系统管理
                    </h3>
                    
                    <!-- 用户管理 -->
                    <div class="bg-blue-500 bg-opacity-20 border border-blue-400 border-opacity-30 rounded-lg p-6 mb-6">
                        <h4 class="text-lg font-semibold text-blue-300 mb-4">
                            <i class="fas fa-users mr-2"></i>
                            用户管理
                        </h4>

                        <div class="mb-6">
                            <div class="flex justify-between items-center mb-4">
                                <h5 class="font-semibold text-white">
                                    <i class="fas fa-database mr-2"></i>
                                    已创建的用户和数据库
                                </h5>
                                <button @click="loadUserList"
                                        :disabled="isLoadingUsers"
                                        class="bg-blue-500 bg-opacity-80 hover:bg-opacity-100 text-white font-semibold py-2 px-4 rounded-lg transition-all duration-300 flex items-center space-x-2 disabled:opacity-50">
                                    <i v-if="isLoadingUsers" class="fas fa-spinner loading-spinner"></i>
                                    <i v-else class="fas fa-sync-alt"></i>
                                    <span>{{ isLoadingUsers ? '加载中...' : '刷新列表' }}</span>
                                </button>
                            </div>

                            <div class="overflow-x-auto">
                                <table class="w-full text-sm text-left text-white">
                                    <thead class="text-xs text-white text-opacity-80 uppercase bg-white bg-opacity-10">
                                        <tr>
                                            <th scope="col" class="px-6 py-3">身份标识</th>
                                            <th scope="col" class="px-6 py-3">数据库名</th>
                                            <th scope="col" class="px-6 py-3">用户名</th>
                                            <th scope="col" class="px-6 py-3">密码</th>
                                            <th scope="col" class="px-6 py-3">创建时间</th>
                                            <th scope="col" class="px-6 py-3">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-if="isLoadingUsers">
                                            <td colspan="6" class="px-6 py-4 text-center text-white text-opacity-60">
                                                <i class="fas fa-spinner loading-spinner mr-2"></i>
                                                加载中...
                                            </td>
                                        </tr>
                                        <tr v-else-if="userList.length === 0">
                                            <td colspan="6" class="px-6 py-4 text-center text-white text-opacity-60">
                                                暂无用户记录
                                            </td>
                                        </tr>
                                        <tr v-else v-for="user in userList" :key="user.id" class="bg-white bg-opacity-5 border-b border-white border-opacity-10 hover:bg-opacity-10 transition-colors">
                                            <td class="px-6 py-4 whitespace-nowrap font-medium text-white">{{ user.identity_key }}</td>
                                            <td class="px-6 py-4 whitespace-nowrap text-white text-opacity-80">{{ user.db_name }}</td>
                                            <td class="px-6 py-4 whitespace-nowrap text-white text-opacity-80">{{ user.db_user }}</td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <button @click="togglePasswordVisibility(user.id)"
                                                        class="text-blue-300 hover:text-blue-200 transition-colors text-sm">
                                                    <i :class="`fas ${passwordVisibility[user.id] ? 'fa-eye-slash' : 'fa-eye'} mr-1`"></i>
                                                    {{ passwordVisibility[user.id] ? '隐藏' : '显示' }}
                                                </button>
                                                <span v-if="passwordVisibility[user.id]" class="ml-2 text-white text-opacity-80 font-mono text-sm">
                                                    {{ getUserPassword(user.identity_key) }}
                                                </span>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-white text-opacity-80 text-sm">
                                                {{ formatDate(user.created_at) }}
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <button @click="confirmDeleteUser(user)"
                                                        class="text-red-300 hover:text-red-200 transition-colors">
                                                    <i class="fas fa-trash mr-1"></i>
                                                    删除
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- 危险操作区域 -->
                    <div class="bg-red-500 bg-opacity-20 border border-red-500 border-opacity-30 rounded-lg p-6">
                        <h4 class="text-lg font-semibold text-red-300 mb-4">
                            <i class="fas fa-exclamation-triangle mr-2"></i>
                            危险操作区域
                        </h4>
                        
                        <div class="mb-6">
                            <h5 class="font-semibold text-white mb-2">
                                <i class="fas fa-trash mr-2"></i>
                                删除用户数据库
                            </h5>
                            <p class="text-white text-opacity-70 text-sm mb-4">
                                此操作将永久删除用户的数据库和所有数据，请谨慎操作！
                            </p>
                            
                            <form @submit.prevent="deleteUser" class="space-y-4">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-white text-opacity-80 text-sm font-medium mb-2">
                                            身份标识
                                        </label>
                                        <input v-model="deleteForm.identity_key" 
                                               type="text" 
                                               placeholder="输入要删除的用户身份标识"
                                               class="w-full px-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-lg text-white placeholder-white placeholder-opacity-60 focus:outline-none focus:ring-2 focus:ring-red-400 focus:ring-opacity-50 transition-all"
                                               required>
                                    </div>
                                    <div>
                                        <label class="block text-white text-opacity-80 text-sm font-medium mb-2">
                                            删除原因
                                        </label>
                                        <input v-model="deleteForm.reason" 
                                               type="text" 
                                               placeholder="请输入删除原因"
                                               class="w-full px-4 py-3 bg-white bg-opacity-20 border border-white border-opacity-30 rounded-lg text-white placeholder-white placeholder-opacity-60 focus:outline-none focus:ring-2 focus:ring-red-400 focus:ring-opacity-50 transition-all"
                                               required>
                                    </div>
                                </div>
                                
                                <button type="submit" 
                                        :disabled="isDeletingUser"
                                        class="bg-red-500 bg-opacity-80 hover:bg-opacity-100 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300 flex items-center space-x-2 disabled:opacity-50">
                                    <i v-if="isDeletingUser" class="fas fa-spinner loading-spinner"></i>
                                    <i v-else class="fas fa-trash"></i>
                                    <span>{{ isDeletingUser ? '删除中...' : '删除用户' }}</span>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 页脚 -->
        <footer v-if="isAuthenticated" class="text-center py-6">
            <div class="text-white text-opacity-60 space-y-2">
                <p>DormDB v1.0.0 | 管理员面板</p>
                <div class="space-x-4">
                    <a href="/" class="hover:text-white transition-colors">
                        <i class="fas fa-home mr-1"></i>
                        返回主页
                    </a>
                    <a href="/swagger-ui/" target="_blank" class="hover:text-white transition-colors">
                        <i class="fas fa-book mr-1"></i>
                        API 文档
                    </a>
                </div>
            </div>
        </footer>
    </div>

    <script>
        const { createApp, ref, reactive, computed, onMounted, nextTick } = Vue;

        // 配置 Axios
        axios.defaults.withCredentials = true;
        axios.defaults.timeout = 10000;
        
        // 添加请求拦截器
        axios.interceptors.request.use(
            config => {
                // 可以在这里添加认证token等
                return config;
            },
            error => {
                return Promise.reject(error);
            }
        );
        
        // 添加响应拦截器
        axios.interceptors.response.use(
            response => {
                return response;
            },
            error => {
                if (error.response && error.response.status === 401) {
                    // 未授权，可能需要重新登录
                    console.log('未授权访问，请重新登录');
                }
                return Promise.reject(error);
            }
        );

        createApp({
            setup() {
                // 响应式数据
                const isAuthenticated = ref(false);
                const isLoggingIn = ref(false);
                const isRefreshing = ref(false);
                const loginPassword = ref('');
                const loginError = ref('');
                const activeTab = ref('applications');
                const studentSubTab = ref('list');
                
                // Toast 通知
                const toasts = ref([]);
                let toastId = 0;
                
                // 系统数据
                const systemStatus = ref({});
                const applicationStats = ref({});
                const recentApplications = ref([]);
                
                // 学号管理
                const studentStats = ref({});
                const studentList = ref([]);
                const newStudent = reactive({
                    student_id: '',
                    student_name: '',
                    class_info: ''
                });
                const isAddingStudent = ref(false);
                
                // 批量导入
                const importData = ref('');
                const overwriteExisting = ref(false);
                const isImporting = ref(false);
                const importResult = ref(null);
                
                // 用户管理
                const userList = ref([]);
                const isLoadingUsers = ref(false);
                const passwordVisibility = ref({});

                // 删除用户
                const deleteForm = reactive({
                    identity_key: '',
                    reason: ''
                });
                const isDeletingUser = ref(false);
                
                // 标签页配置
                const tabs = [
                    { id: 'applications', name: '申请记录', icon: 'fas fa-list' },
                    { id: 'students', name: '学号管理', icon: 'fas fa-graduation-cap' },
                    { id: 'system', name: '系统管理', icon: 'fas fa-cogs' }
                ];
                
                // Toast 方法
                const showToast = (type, title, message = '', duration = 3000) => {
                    const toast = {
                        id: ++toastId,
                        type,
                        title,
                        message
                    };
                    toasts.value.push(toast);
                    
                    setTimeout(() => {
                        removeToast(toast.id);
                    }, duration);
                };
                
                const removeToast = (id) => {
                    const index = toasts.value.findIndex(toast => toast.id === id);
                    if (index > -1) {
                        toasts.value.splice(index, 1);
                    }
                };
                
                const getToastClass = (type) => {
                    const classes = {
                        success: 'bg-green-500 text-white',
                        error: 'bg-red-500 text-white',
                        warning: 'bg-yellow-500 text-white',
                        info: 'bg-blue-500 text-white'
                    };
                    return classes[type] || classes.info;
                };
                
                const getToastIcon = (type) => {
                    const icons = {
                        success: 'fas fa-check-circle',
                        error: 'fas fa-exclamation-circle',
                        warning: 'fas fa-exclamation-triangle',
                        info: 'fas fa-info-circle'
                    };
                    return icons[type] || icons.info;
                };
                
                // 登录方法
                const login = async () => {
                    if (!loginPassword.value.trim()) {
                        loginError.value = '请输入管理员密码';
                        return;
                    }
                    
                    isLoggingIn.value = true;
                    loginError.value = '';
                    
                    try {
                        const response = await axios.post('/api/v1/admin/login', {
                            password: loginPassword.value
                        });
                        
                        const data = response.data;
                        
                        if (data.code === 0) {
                            isAuthenticated.value = true;
                            loginPassword.value = '';
                            showToast('success', '登录成功', '正在加载管理面板...');
                            
                            // 延迟加载数据，让用户看到成功提示
                            setTimeout(() => {
                                refreshData();
                            }, 500);
                        } else {
                            loginError.value = data.message || '密码错误，请重试';
                            showToast('error', '登录失败', data.message || '密码错误，请重试');
                        }
                    } catch (error) {
                        loginError.value = '网络连接错误，请检查网络后重试';
                        showToast('error', '网络错误', '无法连接到服务器');
                        console.error('登录错误:', error);
                    } finally {
                        isLoggingIn.value = false;
                    }
                };
                
                const logout = () => {
                    isAuthenticated.value = false;
                    showToast('info', '已退出登录', '感谢使用管理面板');
                };
                
                // 数据刷新
                const refreshData = async () => {
                    isRefreshing.value = true;
                    
                    try {
                        await Promise.all([
                            loadSystemStatus(),
                            loadApplicationStats(),
                            loadStudentStats()
                        ]);
                        
                        if (studentSubTab.value === 'list') {
                            await loadStudentList();
                        }
                        
                        showToast('success', '刷新成功', '数据已更新');
                    } catch (error) {
                        showToast('error', '刷新失败', '无法获取最新数据');
                        console.error('刷新数据错误:', error);
                    } finally {
                        isRefreshing.value = false;
                    }
                };
                
                // 加载系统状态
                const loadSystemStatus = async () => {
                    try {
                        const response = await axios.get('/api/v1/admin/status');
                        const data = response.data;
                        
                        if (data.code === 0) {
                            systemStatus.value = data.data;
                        } else {
                            throw new Error(data.message);
                        }
                    } catch (error) {
                        console.error('加载系统状态失败:', error);
                        throw error;
                    }
                };
                
                // 加载申请统计
                const loadApplicationStats = async () => {
                    try {
                        const response = await axios.get('/api/v1/admin/stats');
                        const data = response.data;
                        
                        if (data.code === 0) {
                            applicationStats.value = data.data;
                            recentApplications.value = data.data.recent_applications || [];
                        } else {
                            throw new Error(data.message);
                        }
                    } catch (error) {
                        console.error('加载申请统计失败:', error);
                        throw error;
                    }
                };
                
                // 学号管理方法
                const loadStudentStats = async () => {
                    try {
                        const response = await axios.get('/api/v1/admin/student-ids/stats');
                        const data = response.data;
                        
                        if (data.code === 0) {
                            studentStats.value = data.data;
                        } else {
                            console.error('获取学号统计失败:', data.message);
                        }
                    } catch (error) {
                        console.error('获取学号统计失败:', error);
                    }
                };
                
                const loadStudentList = async () => {
                    try {
                        const response = await axios.get('/api/v1/admin/student-ids?limit=100&offset=0');
                        const data = response.data;
                        
                        if (data.code === 0) {
                            studentList.value = data.data;
                        } else {
                            showToast('error', '加载失败', data.message || '无法获取学号列表');
                        }
                    } catch (error) {
                        showToast('error', '数据加载失败', '无法获取学号列表');
                        console.error('加载学号列表失败:', error);
                    }
                };
                
                const addStudent = async () => {
                    if (!newStudent.student_id.trim()) {
                        showToast('error', '表单错误', '请输入学号');
                        return;
                    }
                    
                    isAddingStudent.value = true;
                    
                    try {
                        const response = await axios.post('/api/v1/admin/student-ids', {
                            student_id: newStudent.student_id,
                            student_name: newStudent.student_name || null,
                            class_info: newStudent.class_info || null
                        });
                        
                        const data = response.data;
                        
                        if (data.code === 0) {
                            showToast('success', '添加成功', '学号信息已成功添加');
                            
                            // 重置表单
                            newStudent.student_id = '';
                            newStudent.student_name = '';
                            newStudent.class_info = '';
                            
                            // 刷新数据
                            await loadStudentStats();
                            if (studentSubTab.value === 'list') {
                                await loadStudentList();
                            }
                        } else {
                            showToast('error', '添加失败', data.message || '操作未能完成');
                        }
                    } catch (error) {
                        showToast('error', '网络错误', '无法连接到服务器');
                        console.error('添加学号失败:', error);
                    } finally {
                        isAddingStudent.value = false;
                    }
                };
                
                const batchImportStudents = async () => {
                    if (!importData.value.trim()) {
                        showToast('error', '表单错误', '请输入要导入的学号数据');
                        return;
                    }
                    
                    isImporting.value = true;
                    importResult.value = null;
                    
                    try {
                        const response = await axios.post('/api/v1/admin/student-ids/batch-import', {
                            student_data: importData.value,
                            overwrite_existing: overwriteExisting.value
                        });
                        
                        const data = response.data;
                        
                        if (data.code === 0) {
                            importResult.value = {
                                success: true,
                                data: data.data
                            };
                            
                            showToast('success', '导入完成', `成功导入 ${data.data.imported_count} 条，更新 ${data.data.updated_count} 条`);
                            
                            // 清空输入
                            importData.value = '';
                            
                            // 刷新数据
                            await loadStudentStats();
                            if (studentSubTab.value === 'list') {
                                await loadStudentList();
                            }
                        } else {
                            importResult.value = {
                                success: false,
                                message: data.message
                            };
                            
                            showToast('error', '导入失败', data.message || '操作未能完成');
                        }
                    } catch (error) {
                        importResult.value = {
                            success: false,
                            message: '网络连接错误'
                        };
                        
                        showToast('error', '网络错误', '无法连接到服务器');
                        console.error('批量导入失败:', error);
                    } finally {
                        isImporting.value = false;
                    }
                };
                
                const editStudent = (student) => {
                    showToast('info', '功能提示', '编辑功能正在开发中...');
                };
                
                const deleteStudent = async (id) => {
                    if (!confirm('确定要删除这个学号吗？')) {
                        return;
                    }
                    
                    try {
                        const response = await axios.delete(`/api/v1/admin/student-ids/${id}`);
                        
                        const data = response.data;
                        
                        if (data.code === 0) {
                            showToast('success', '删除成功', '学号信息已成功删除');
                            await loadStudentList();
                            await loadStudentStats();
                        } else {
                            showToast('error', '删除失败', data.message || '操作未能完成');
                        }
                    } catch (error) {
                        showToast('error', '网络错误', '无法连接到服务器');
                        console.error('删除学号失败:', error);
                    }
                };
                
                // 用户管理方法
                const loadUserList = async () => {
                    isLoadingUsers.value = true;
                    try {
                        const response = await axios.get('/api/v1/admin/users');
                        const data = response.data;

                        if (data.code === 0) {
                            userList.value = data.data;
                        } else {
                            showToast('error', '加载失败', data.message || '无法获取用户列表');
                        }
                    } catch (error) {
                        showToast('error', '网络错误', '无法连接到服务器');
                        console.error('加载用户列表失败:', error);
                    } finally {
                        isLoadingUsers.value = false;
                    }
                };

                const togglePasswordVisibility = (userId) => {
                    passwordVisibility.value[userId] = !passwordVisibility.value[userId];
                };

                const getUserPassword = (identityKey) => {
                    // 这里应该从安全的地方获取密码，暂时显示占位符
                    // 实际应用中，密码不应该在前端明文显示
                    return '••••••••••';
                };

                const confirmDeleteUser = (user) => {
                    deleteForm.identity_key = user.identity_key;
                    deleteForm.reason = '';

                    // 滚动到删除表单
                    const deleteSection = document.querySelector('.bg-red-500');
                    if (deleteSection) {
                        deleteSection.scrollIntoView({ behavior: 'smooth' });
                    }

                    showToast('info', '请填写删除原因', `准备删除用户: ${user.identity_key}`);
                };

                const formatDate = (dateString) => {
                    try {
                        return new Date(dateString).toLocaleString('zh-CN');
                    } catch {
                        return dateString;
                    }
                };

                // 删除用户
                const deleteUser = async () => {
                    if (!deleteForm.identity_key.trim() || !deleteForm.reason.trim()) {
                        showToast('error', '表单错误', '请填写完整信息');
                        return;
                    }
                    
                    if (!confirm(`确定要删除用户 "${deleteForm.identity_key}" 吗？\n删除原因：${deleteForm.reason}\n\n此操作不可撤销！`)) {
                        return;
                    }
                    
                    isDeletingUser.value = true;
                    
                    try {
                        const response = await axios.delete(`/api/v1/admin/users/${deleteForm.identity_key}`, {
                            data: {
                                reason: deleteForm.reason
                            }
                        });
                        
                        const data = response.data;
                        
                        if (data.code === 0) {
                            showToast('success', '操作成功', '用户数据已成功删除');
                            
                            // 清空表单
                            deleteForm.identity_key = '';
                            deleteForm.reason = '';
                            
                            // 刷新数据
                            refreshData();
                            loadUserList();
                        } else {
                            showToast('error', '删除失败', data.message || '操作未能完成');
                        }
                    } catch (error) {
                        showToast('error', '网络错误', '无法连接到服务器');
                        console.error('删除用户错误:', error);
                    } finally {
                        isDeletingUser.value = false;
                    }
                };
                
                // 工具方法
                const getStatusIndicator = (status) => {
                    switch (status) {
                        case '正常': return 'bg-green-400';
                        case '异常': return 'bg-red-400';
                        default: return 'bg-yellow-400';
                    }
                };
                
                const formatDateTime = (dateString) => {
                    const date = new Date(dateString);
                    return date.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                };
                
                // 监听标签页切换
                const handleTabChange = async () => {
                    if (activeTab.value === 'students' && studentSubTab.value === 'list') {
                        await loadStudentList();
                    }
                };
                
                // 监听学号子标签页切换
                const handleStudentSubTabChange = async () => {
                    if (studentSubTab.value === 'list') {
                        await loadStudentList();
                    } else if (studentSubTab.value === 'import') {
                        importResult.value = null;
                    }
                };
                
                // 组件挂载时初始化
                onMounted(() => {
                    // 显示欢迎提示
                    setTimeout(() => {
                        showToast('info', '欢迎使用', 'DormDB 管理员面板已准备就绪');
                    }, 500);

                    // 初始化用户列表
                    loadUserList();
                });
                
                return {
                    // 响应式数据
                    isAuthenticated,
                    isLoggingIn,
                    isRefreshing,
                    loginPassword,
                    loginError,
                    activeTab,
                    studentSubTab,
                    toasts,
                    systemStatus,
                    applicationStats,
                    recentApplications,
                    studentStats,
                    studentList,
                    newStudent,
                    isAddingStudent,
                    importData,
                    overwriteExisting,
                    isImporting,
                    importResult,
                    userList,
                    isLoadingUsers,
                    passwordVisibility,
                    deleteForm,
                    isDeletingUser,
                    tabs,
                    
                    // 方法
                    showToast,
                    removeToast,
                    getToastClass,
                    getToastIcon,
                    login,
                    logout,
                    refreshData,
                    loadSystemStatus,
                    loadApplicationStats,
                    loadStudentStats,
                    loadStudentList,
                    addStudent,
                    batchImportStudents,
                    editStudent,
                    deleteStudent,
                    loadUserList,
                    togglePasswordVisibility,
                    getUserPassword,
                    confirmDeleteUser,
                    formatDate,
                    deleteUser,
                    getStatusIndicator,
                    formatDateTime,
                    handleTabChange,
                    handleStudentSubTabChange
                };
            }
        }).mount('#app');
    </script>
</body>
</html>
